package com.linghang.demo.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.linghang.demo.domain.Homepic;
import com.linghang.demo.domain.HomepicExample;
import com.linghang.demo.mapper.HomepicMapper;
import com.linghang.demo.req.HomepicQueryReq;
import com.linghang.demo.req.HomepicSaveReq;
import com.linghang.demo.resp.HomepicQueryResp;
import com.linghang.demo.resp.PageResp;
import com.linghang.demo.util.CopyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class HomepicService {
    private int id=10;
    @Resource
    private HomepicMapper homepicMapper;
    private static final Logger LOG = LoggerFactory.getLogger(HomepicService.class);

    public List<Homepic> list(){
        return homepicMapper.selectByExample(null);
    }

    public PageResp<HomepicQueryResp> list(HomepicQueryReq req) {
        HomepicExample homepicExample = new HomepicExample();
        HomepicExample.Criteria criteria = homepicExample.createCriteria();
        if (!ObjectUtils.isEmpty(req.getId())) {
            criteria.andIdEqualTo(  req.getId() );
        }

        PageHelper.startPage(req.getPage(), req.getSize());
        List<Homepic> homepicList = homepicMapper.selectByExample(homepicExample);

        PageInfo<Homepic> pageInfo = new PageInfo<>(homepicList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        // List<HomepicResp> respList = new ArrayList<>();
        // for (Homepic homepic : homepicList) {
        //     // HomepicResp homepicResp = new HomepicResp();
        //     // BeanUtils.copyProperties(homepic, homepicResp);
        //     // 对象复制
        //     HomepicResp homepicResp = CopyUtil.copy(homepic, HomepicResp.class);
        //
        //     respList.add(homepicResp);
        // }

        // 列表复制
        List<HomepicQueryResp> list = CopyUtil.copyList(homepicList, HomepicQueryResp.class);

        PageResp<HomepicQueryResp> pageResp = new PageResp();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);

        return pageResp;
    }

    /**
     * 保存
     */
    public void save(HomepicSaveReq req) {
        Homepic homepic = CopyUtil.copy(req, Homepic.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            homepic.setId(id++);
            homepicMapper.insert(homepic);
        } else {
            // 更新
            homepicMapper.updateByPrimaryKey(homepic);
        }
    }

    
    public void  delete(int id){
        homepicMapper.deleteByPrimaryKey(id);
    }
}
